package service

import (
	"errors"
	"fmt"
	"www.bwbdim.com/internal/dao"
	"www.bwbdim.com/internal/dto"
	"www.bwbdim.com/pkg"
)

type UsersServiceImpl interface {
	Login(req dto.LoginReq) (resp *dto.LoginResp, err error)
}

type UsersService struct {
	md5 *pkg.Md5s
}

func NewUsersService() *UsersService {
	return &UsersService{
		pkg.NewNd5(),
	}
}

func (u *UsersService) Login(req dto.LoginReq) (resp *dto.LoginResp, err error) {
	usersDao := dao.NewUsersDao()

	req.Password = u.md5.SetMd5(req.Password)

	login, rows, err := usersDao.Login(req)

	fmt.Println(login, rows)

	if err != nil {
		return nil, err
	}

	if rows <= 0 {
		return nil, errors.New("账号密码错误")
	}

	//根据用户信息生成token
	tokenString, err := pkg.NewJwt().TokenEncode(login.Id)
	if err != nil {
		return nil, err
	}

	//根据token 及 用户信息 完成 redis缓存用户信息
	_, err = usersDao.SetTokenToRedis(tokenString, login)

	if err != nil {
		return nil, err
	}
	//返回登录状态  成功  ，nil

	return &dto.LoginResp{Token: tokenString}, nil

}
